package risk.control.application.activity.make;


import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import risk.control.application.MainApplication;
import risk.control.application.R;
import risk.control.application.activity.base.BaseActivity;
import risk.control.application.activity.major.MainActivity;
import risk.control.application.activity.major.WithdrawalBean;
import risk.control.application.activity.myself.MyselfActivity;
import risk.control.application.component.channel.ChannelClickListener;
import risk.control.application.component.channel.ChannelDialog;
import risk.control.application.component.currency.CurrencyClickListener;
import risk.control.application.component.currency.CurrencyDialog;
import risk.control.application.entity.TransactionRecordBean;
import risk.control.application.utils.CameraPermissionHelper;
import risk.control.application.utils.DateTimePickerUtil;
import risk.control.application.utils.LogUtils;
import risk.control.application.utils.RouteJump;
import risk.control.application.utils.ToastUtils;

/**
 * 预约页面
 */
public class MakeActivity extends BaseActivity implements LifecycleOwner {

    private TextView mTvTitle;
    private Button mBtnTakePic;

    private Button mBtnNext;

    //取款时间
    private LinearLayout llTimeItem;
    private TextView mTvTime;
    private TextView mTvTimeTitle;

    //取款金额
    private TextView mTvAmountTitle;
    private EditText mEdAmount;

    //币种
    private LinearLayout llCurrencyType;
    private TextView mTvCurrencyType;

    //交易渠道
    private LinearLayout llChannel;
    private TextView mTvChannel;

    //是否本人
    private ListView mLvMyself;
    private List<MyselfBean> mMyselfList;
    private MyselfAdapter mAdapter;

    //取款理由
    private LinearLayout mllReason;

    //摄像头权限
    private ActivityResultLauncher<String> cameraPermissionLauncher;
    private CameraPermissionHelper.PermissionCallback permissionCallback;

    private BroadcastReceiver mReceiver;

    private EditText mEtUserName;
    private EditText mEtIdNumber;
    private EditText mEtPhoneNumber;
    private EditText mEtReason;
    private EditText mEtPlace;

    @Override
    protected void postData(HashMap<String, String> dataMap) {
        if (mEtUserName != null) {
            mEtUserName.setText(dataMap.get("userName"));
        }
        if (mEtIdNumber != null) {
            mEtIdNumber.setText(dataMap.get("idNumber"));
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_make);
        intiView();
        intiData();
        initListener();
    }


    private void intiView() {
        mTvTitle = findViewById(R.id.tv_result_title);
        mBtnTakePic = findViewById(R.id.btn_take_pic);
        mBtnNext = findViewById(R.id.btn_next);

        llTimeItem = findViewById(R.id.ll_time);
        mTvTime = findViewById(R.id.tv_time);
        mTvTimeTitle = findViewById(R.id.tv_time_title);

        llCurrencyType = findViewById(R.id.ll_currency_type);
        mTvCurrencyType = findViewById(R.id.tv_currency_type);

        llChannel = findViewById(R.id.ll_channel);
        mTvChannel = findViewById(R.id.tv_channel);

        mTvAmountTitle = findViewById(R.id.tv_amount_title);
        mEdAmount = findViewById(R.id.edit_amount);

        mLvMyself = findViewById(R.id.lv_myself);

        mllReason = findViewById(R.id.ll_reason);

        mEtUserName = findViewById(R.id.edit_name);
        mEtIdNumber = findViewById(R.id.edit_id_number);
        mEtPhoneNumber = findViewById(R.id.edit_phone);
        mEtReason = findViewById(R.id.ed_reason);
        mEtPlace = findViewById(R.id.ed_place);
    }

    private void intiData() {
        //接收数据
        Bundle bundle = getIntent().getExtras();
        if (bundle == null) {
            finish();
            return;
        }
        String title = bundle.getString("title");
        mTvTitle.setText(title);
        mTvTime.setText(getCurrentTime());//设置当前时间
        mTvCurrencyType.setText("人民币");//设置币种
        mTvChannel.setText("柜面");//设置币种
        //是否本人预约
        MyselfBean bean = new MyselfBean();
        bean.isSelect = "0";
        bean.des = "本人";
        MyselfBean bean1 = new MyselfBean();
        bean1.isSelect = "1";
        bean1.des = "非本人";
        if (mMyselfList == null) {
            mMyselfList = new ArrayList<>();
        } else {
            mMyselfList.clear();
        }
        mMyselfList.add(bean);
        mMyselfList.add(bean1);
        //设置适配器
        mAdapter = new MyselfAdapter(this, mMyselfList);
        mLvMyself.setAdapter(mAdapter);
        registerReceiver();
        //根据标题展示不同页面
        if (title != null && title.equals("现场取款")) {
            //现场取款
            mTvTimeTitle.setText("取款时间");
            //取款金额
            mTvAmountTitle.setText("取现金额");
            //交易渠道
            llChannel.setVisibility(VISIBLE);
            //取款理由
            mllReason.setVisibility(VISIBLE);
        } else {
            //预约取款
            mTvTimeTitle.setText("预约取款时间");
            //预约取款金额
            mTvAmountTitle.setText("预约取现金额");
            //交易渠道
            llChannel.setVisibility(GONE);
            //取款理由
            mllReason.setVisibility(GONE);
        }
    }


    private void initListener() {
        //权限回调
        permissionCallback = new CameraPermissionHelper.PermissionCallback() {
            @Override
            public void onPermissionGranted() {
                //跳转页面
                startIDCarScanActivity();
            }
        };
        // 创建权限请求Launcher
        cameraPermissionLauncher = CameraPermissionHelper.createPermissionLauncher(this, permissionCallback);
        mBtnTakePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查并请求摄像头权限
                CameraPermissionHelper.requestCameraPermission(MakeActivity.this, cameraPermissionLauncher, permissionCallback);
            }
        });

        //是否本人
        mLvMyself.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int size = mMyselfList.size();
                for (int i = 0; i < size; i++) {
                    MyselfBean bean = mMyselfList.get(i);
                    if (i == position) {
                        bean.isSelect = "0";
                    } else {
                        bean.isSelect = "1";
                    }
                }
                mAdapter.refreshData(mMyselfList);//刷新页面
            }
        });

        //时间选择
        llTimeItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用日期时间选择器
                DateTimePickerUtil.showDateTimePicker(MakeActivity.this, new DateTimePickerUtil.DateTimePickerListener() {
                    @Override
                    public void onDateTimeSelected(String dateTimeString) {
                        // 处理返回的时间字符串，格式为 "yyyy-MM-dd HH:mm"
                        mTvTime.setText(dateTimeString);
                    }
                });
            }
        });

        //币种选择
        llCurrencyType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String curryStr = mTvCurrencyType.getText().toString();//当前的交易渠道
                CurrencyDialog dialog = new CurrencyDialog(MakeActivity.this, curryStr);
                dialog.showDialog();
                dialog.setBtnClickListener(new CurrencyClickListener() {
                    @Override
                    public void onPositiveClick(String currencyType) {
                        mTvCurrencyType.setText(currencyType);//设置交易渠道
                    }
                });
            }
        });

        //交易渠道选择
        llChannel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String curryStr = mTvChannel.getText().toString();//当前的币种
                ChannelDialog dialog = new ChannelDialog(MakeActivity.this, curryStr);
                dialog.showDialog();
                dialog.setBtnClickListener(new ChannelClickListener() {
                    @Override
                    public void onPositiveClick(String currencyType) {
                        mTvChannel.setText(currencyType);//设置币种
                    }
                });
            }
        });

        mBtnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转预约页面
                int size = mMyselfList.size();
                for (int i = 0; i < size; i++) {
                    MyselfBean bean = mMyselfList.get(i);
                    String isSelect = bean.isSelect;
                    String des = bean.des;
                    if (isSelect.equals("0")) {
                        //写入全局数据
                        TransactionRecordBean transactionRecordBean = MainApplication.transactionRecordBean;
                        /*
                         * 姓名
                         * 身份证号
                         * 手机号
                         * 取款时间
                         * 取现金额
                         * 币种
                         * 交易渠道
                         * 取款理由
                         * 开卡地
                         * 是否本人取款
                         */
                        String withdrawalsName = mEtUserName.getText().toString();
                        String idNumber = mEtIdNumber.getText().toString();
                        String phoneNumber = mEtPhoneNumber.getText().toString();
                        String withdrawalTime = mTvTime.getText().toString();//时间
                        String withdrawalAmount = mEdAmount.getText().toString();//金额
                        String currency = mTvCurrencyType.getText().toString();//币种
                        String transactionChannel = mTvChannel.getText().toString();//交易渠道
                        String withdrawalReason = mEtReason.getText().toString();//取款理由
                        String cardIssuancePlace = mEtPlace.getText().toString();
                        if (cardIssuancePlace.isEmpty()) {
                            //如果等于空默认获取清远
                            cardIssuancePlace = mEtPlace.getHint().toString();
                        }
                        transactionRecordBean.withdrawalsName = withdrawalsName;
                        transactionRecordBean.idNumber = idNumber;
                        transactionRecordBean.phoneNumber = phoneNumber;
                        transactionRecordBean.withdrawalTime = withdrawalTime;
                        transactionRecordBean.withdrawalAmount = withdrawalAmount;
                        transactionRecordBean.currency = currency;
                        transactionRecordBean.transactionChannel = transactionChannel;
                        transactionRecordBean.withdrawalReason = withdrawalReason;
                        transactionRecordBean.cardIssuancePlace = cardIssuancePlace;
                        transactionRecordBean.isSelfWithdrawal = des;
                        Map<String, Object> params = new HashMap<>();
                        params.put("title", des);
                        RouteJump.start(MakeActivity.this, RouteJump.MYSELF_ACTION, params, false, true);
                    }
                }
            }
        });


    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("destroy-activity-action");//关闭当前页面
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                finish();
            }
        };
        //只允许接受本app
        ContextCompat.registerReceiver(this, mReceiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }

    //获取当前时间
    @SuppressLint("SimpleDateFormat")
    public static String getCurrentTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(System.currentTimeMillis());
    }

}





